<?php
/**
 * Created by PhpStorm.
 * User: m1514
 * Date: 2017/1/4
 * Time: 16:21
 */

namespace Home\Controller;


use Common\Model\CargoListModel;
use Common\Model\CommodityModel;
use Common\Model\GenrdAttrModel;
use Org\Util\Cart;

class ContentController extends HomeQController
{
    public function index(){
        $conf=[
            'js'=>['list']
        ];
        $this->assign('conf',$conf);
        $confData=[
            'css'=>['index']
        ];
        $this->assign('confData',$confData);
        //获取get中的gid
        $gid=I('get.gid');
        //商品表和商品详情表关联获取等于gid的这一条
        $data=(new CommodityModel())->alias('g')->join("shop_detail d on g.gid=d.gid")->where("g.gid={$gid}")->find();
        $data['big'] = explode(',', $data['big']);
        $data['medium'] = explode(',', $data['medium']);
        $data['small'] = explode(',', $data['small']);
        $this->assign('data',$data);
        //获取规格数据
        $goodsList=(new GenrdAttrModel())->alias('ta')->join("shop_goods_attr ga on ta.taid=ga.taid")->where("gid={$gid} and ta.class=1")->select();
        $temp=[];
        foreach($goodsList as $k=>$v){
            $temp[$v['taname']][]=$v;
        }
        $this->assign('temp',$temp);
//        dd($data);
//        dd($temp);

        //显示模板
        $this->display();
    }

    //异步回去货品库存
    public function ajaxGetTotal(){
        if(IS_AJAX){
            $data['gid']=I('post.gid');
            $data['combine']=rtrim(I('post.combine'),',');
            //根据两个参数在货品列表查询库存
            $data=(new CargoListModel())->where("gid={$data['gid']} and combine='{$data['combine']}'")->find();
//            dd($data);die;

            if(!$data){//如果没有这条数据的话，我们视为没有存货
                echo json_encode(['valid'=>0,'message'=>'']);die;
            }else{//如果到这里就说明查出数据，并且有现货
                echo json_encode(['valid'=>1,'message'=>'','inventory'=>$data['inventory']]);die;
            }

        }
    }
    /**
     * 异步添加购物车
     */
    public function ajaxAddCart()
    {
        if(IS_AJAX){
            $data['gid'] = $_POST['gid'];
            $data['num'] = $_POST['num'];
            $data['options'] = $_POST['options'];
            //根据商品id在商品表中获得商品名称以及价格
            $oneGoodsData = (new CommodityModel())->where("gid={$data['gid']}")->field('gname,shopprice')->find();
//            dd($oneGoodsData);die;
            $data = [
                'id'        => $data['gid'], // 商品 ID
                'name'      =>$oneGoodsData['gname'],// 商品名称
                'num'       => $data['num'], // 商品数量
                'price'     => $oneGoodsData['shopprice'], // 商品价格
                'options'   => $data['options'],// 其他参数如价格、颜色、可以为数组或字符串
            ];
            (new Cart())->add($data);
            echo 1;exit;
        }
    }
}